import { Message } from 'element-ui'
class WebSocketClass {
    constructor(name) {
        this.name = name;
        this.connect(name);
    }

    connect(name) {
        this.ws = new WebSocket(name);
        this.ws.onopen = e => {
            this.status = 'open';
            // Message.success('实时库连接成功');
            console.log(`${name}连接成功`, e);
        };
        this.ws.onerror = e =>{
            // Message.warning('实时库连接出错，正在重新连接!')
            if(this.ws)close();
            setTimeout(()=>{
                this.connect(this.name);
            },1500)
        }
    }
    sendMessage = message => {
        setTimeout(() => {
            if (this.ws.readyState === 0) {
                this.sendMessage(message)
            } else {
                this.ws.send(JSON.stringify(message))
            }
        }, 1000)
    }
    getMessage(resMethods) {
        this.ws.onmessage = e => {
            resMethods(e.data)
        };
    }

    close() {
        // this.ws.send('close');
        this.ws.close();
        console.log('关闭成功'+new Date());
    }
}

export default WebSocketClass;
